﻿var toolbar = null;
var editor = null;
$(document).ready(function () {
    var toolbar = [
        ['undo', 'redo', '|',
            'bold', 'italic', 'underline', 'fontborder', 'strikethrough', 'superscript', 'subscript', 'removeformat', 'formatmatch', 'autotypeset', 'blockquote', 'pasteplain', '|', 'forecolor', 'backcolor', 'insertorderedlist', 'insertunorderedlist', 'selectall', 'cleardoc', '|',
            'rowspacingtop', 'rowspacingbottom', 'lineheight', '|',
            'customstyle', 'paragraph', 'fontfamily', 'fontsize', '|',
            'directionalityltr', 'directionalityrtl', 'indent', '|',
            'justifyleft', 'justifycenter', 'justifyright', 'justifyjustify', '|', 'touppercase', 'tolowercase', '|',
            'pagebreak', 'horizontal', 'date', 'time', '|', 
            'inserttable', 'deletetable', 'insertparagraphbeforetable', 'insertrow', 'deleterow', 'insertcol', 'deletecol', 'mergecells', 'mergeright', 'mergedown', 'splittocells', 'splittorows', 'splittocols', 'charts', '|', 
        ]
    ];
    var editor = UE.getEditor('editor-text-area', { zIndex: 9801, autoHeightEnabled: true, toolbars: toolbar });
    editor.ready(function () {
        $("#edui1_toolbarbox").appendTo($("#editor-toolbar"));
        var id = parseInt($("#edit-article-form").find("#DocID").val());//加载内容
        if (id > 0) {
            $.ajax({
                url: "~/News/GetDocumentByID/" + id,
                type: "POST",
                contentType: 'application/json',
                success: function (e) {
                    if (e != null) {
                        UE.getEditor('editor-text-area').setContent(e.DocExt.DocContent);
                        $("#DocumentTypeID").combotree("setValue", e.DocumentTypeID);
                        $("input[radiobuttonname=ContentSourceID]").each(function () {
                            if (this.value == e.ContentSourceID) {
                                $(this).radiobutton("check");
                                return false;
                            }
                        });
                    }
                },
                error: function (e) {
                    alert("error:" + e);
                }
            });
        }
    });

    //上传资源图
    $('#_upload_img_btn').fileupload({
        dropZone: null,
        url: $.Content("~/News/Controller?action=uploadimage"),
        autoUpload: false, maxFileSize: 999000,
        acceptFileTypes: /(\.|\/)(gif|jpe?g|png)$/i,
        disableImageResize: /Android(?!.*Chrome)|Opera/.test(window.navigator.userAgent),
        previewMaxWidth: 100, previewMaxHeight: 100, previewCrop: true
    }).on('fileuploadadd', function (e, data) {
        var imgList = $("#image-panel-list");
        var imgItem = $("<li class='image-item'><img class='img'/></li>");
        data.context = imgItem.appendTo(imgList);
        $.each(data.files, function (index, file) {
            var name = $("<div class='anme' title='" + file.name + "'>" + file.name + "</span>");
            var remove = $("<i class='fa fa-remove remove' title='删除'></i>");
            remove.click(function () { RemoveAttachment(this, $(this).attr("DocID"), $(this).attr("fileId")); });
            var p1 = $("<div style='display:inline-block'></div>");
            var item = $("<div class='img-name'>");
            remove.appendTo(p1); name.appendTo(p1); p1.appendTo(item);
            item.appendTo(data.context);
        });
        data.context.data("data", { jXHR: data.submit() });
    }).on('fileuploaddone', function (e, data) {
        var d = data.result.Data;
        data.context.find(".img").attr("src", d.ImagePath);
        var rm = data.context.find(".remove");
        rm.attr("DocID", d.DocID);
        rm.attr("fileId", d.Id);
        var ck = data.context.find("input[type='checkbox']");
        ck.attr("DocID", d.DocID);
        ck.attr("fileId", d.Id);
    }).on('fileuploadsubmit', function (e, data) {
        var docId = CheckArticleID();
        var userId = CheckArticleUserID();
        data.formData = { DocID: docId, UserID: userId };
    }).prop('disabled', !$.support.fileInput).parent().addClass($.support.fileInput ? undefined : 'disabled');

    //预览图
    $('#_upload_previewImg_btn').fileupload({
        dropZone: null,
        url: $.Content("~/News/Controller?action=uploadPreImage"),
        autoUpload: false, maxFileSize: 999000,
        acceptFileTypes: /(\.|\/)(gif|jpe?g|png)$/i,
        disableImageResize: /Android(?!.*Chrome)|Opera/.test(window.navigator.userAgent),
        previewMaxWidth: 100, previewMaxHeight: 100, previewCrop: true
    }).on('fileuploadadd', function (e, data) {
        var imgItem = $("#docPreviewImg");
        if (imgItem.find('img').length <= 0) { $("<img class='img'>").appendTo(imgItem); }
        data.context = imgItem;
        data.context.data("data", { jXHR: data.submit() });
    }).on('fileuploaddone', function (e, data) {
        var d = data.result.Data;
        data.context.find(".img").attr("src", d.ImagePath);
        data.context.find("span").hide();
    }).on('fileuploadsubmit', function (e, data) {
        var docId = CheckArticleID();
        var userId = CheckArticleUserID();
        data.formData = { DocID: docId, UserID: userId };
    }).prop('disabled', !$.support.fileInput).parent().addClass($.support.fileInput ? undefined : 'disabled');
});

//创作类型
function GetContentSourceID() {
    var v = 0;
    $("input[radiobuttonname=ContentSourceID]").each(function () {
        if ($(this).radiobutton("options").checked) {
            v = parseInt(this.value);
            return false;
        }
    });
    return v;
}

function GetDocumentTypeID(form) {
    var v = parseInt(form.find("#DocumentTypeID").combotree("getValue"));
    if (isNaN(v) || v == null) { v = 0; }

    return v;
}

function CheckArticleID() {
    var form = $("#edit-article-form");
    var id = parseInt(form.find("#DocID").val());
    if (id <= 0) {
        if (SaveArticle(true)) {
            id = parseInt(form.find("#DocID").val());
        }
    }
    return id;
}

function CheckArticleUserID() {
    var form = $("#edit-article-form");
    var id = parseInt(form.find("#UserID").val());
    return id;
}


function SubmitAuditPublish() {
    var form = $("#edit-article-form");
    var id = parseInt(form.find("#DocID").val());
    if (SaveArticle(true)) {
        id = parseInt(form.find("#DocID").val());
        $.ajax({
            url: "~/News/SubmitAudit/" + id,
            type: "POST",
            contentType: 'application/json',
            success: function (e) {
                if (e.Result) {
                    $.messager.alert('提交审核', '提交审核成功！', 'info', function () {
                        location.href = $.Content("~/News/ArticleIndex");
                    });
                } else {
                    $.messager.alert('提交审核', '提交审核失败，请检查必要的信息是否填写!', 'error');
                }
            },
            error: function (e) {
                alert("error:" + e);
            }
        });
    }
}

function SaveArticle(sync) {
    var result = false;
    if (sync == undefined) { sync = false; }
    var form = $("#edit-article-form");
    if (form.form('enableValidation').form('validate')) {
        var editor = UE.getEditor('editor-text-area');
        var item = {
            Id: parseInt(form.find("#DocID").val()),
            ContentType: 1,
            DocumentTypeID: GetDocumentTypeID(form),
            ContentSourceID: GetContentSourceID(),
            Title: form.find("#DocTitle").val(),
            Summary: form.find("#Summary").textbox("getValue"),
            Author: form.find("#Author").textbox("getValue"),
            TargetURL: form.find("#TargetURL").textbox("getValue"),
            DocExt: { DocContent: editor.getContent() },
        };
        item.DocExt.DocID = item.Id;

        $.ajax({
            async: !sync,
            url: "~/News/SaveArticle",
            type: "POST",
            contentType: 'application/json',
            data: JSON.stringify(item),
            success: function (e) {
                if (e.Result) {
                    form.find("#DocID").val(e.Data.Id);
                    form.find("#DocTitle").val(e.Data.Title);
                    result = true;
                    if (!sync) {
                        $.messager.show({
                            msg: '保存成功!',
                            showType: 'show'
                        });
                    }
                }
            },
            error: function (e) {
                alert("error:" + e);
            }
        });
    }
    return result;
}

function RemoveAttachment(p, docId, fileId) {
    $.messager.confirm('删除', '确定要删除图片?', function (r) {
        if (r) {
            $.ajax({
                url: "~/News/RemoveArticleAttachment?docId=" + docId + "&fileId=" + fileId,
                type: "DELETE",
                success: function (e) {
                    if (e.Result) {
                        $(p).parent().parent().parent().remove();
                    } else {
                        $.messager.alert('删除失败', '删除失败!', 'error');
                    }
                },
                error: function (e) {
                    alert("error:" + e);
                }
            });
        }
    });
}
